package org.example.afiona.controller.feign.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.example.afiona.VO.SentinelOrderInfoVO;
import org.example.afiona.common.VO.ResultVO;
import org.example.afiona.common.utils.ResultVOUtil;
import org.example.afiona.service.SentinelOrderFeignApi;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: leo
 * @date: 2021/6/9
 */
@RestController
@ApiIgnore
public class SentinelOrderFeignImpl implements SentinelOrderFeignApi {
    @Override
    @SentinelResource(value = "orderLimit", blockHandler = "handleLimit", fallback = "timeoutHandler")
    public ResultVO<List<SentinelOrderInfoVO>> getOrderListByUserId(Integer userId) {
//        int x = 10/0;
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        List<SentinelOrderInfoVO> orderInfoVOList = Stream.of(1, 2, 3).map(e -> {
            SentinelOrderInfoVO vo = new SentinelOrderInfoVO();
            vo.setOrderId(String.valueOf(e));
            vo.setAmount(new BigDecimal(String.valueOf(e * 100)));
            return vo;
        }).collect(Collectors.toList());
        return ResultVOUtil.success(orderInfoVOList);
    }

    public ResultVO<List<SentinelOrderInfoVO>> handleLimit(Integer userId,BlockException ex) {
        return ResultVOUtil.error(405, "order服务不可用");
    }


    public ResultVO<List<SentinelOrderInfoVO>> timeoutHandler(Integer userId,Throwable e) {

        return ResultVOUtil.error(500, "订单服务不可用，请稍后重试！！！");
    }
}
